package com.fsy.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fsy.entities.MenuInfo;
import com.fsy.entities.Modules;
import com.fsy.entities.Rolemodules;
import com.fsy.service.ModulesService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/menu")
public class MenuController {
    @Resource
    private ModulesService modulesService;

    /**
     * 初始化菜单
     * @param userId
     * @return
     */
    @GetMapping("/init")
    public Map<String, Object> getMenu(Integer userId){
        //1、获取当前登录用户能操作的所有菜单
        List<MenuInfo> initList = modulesService.initMenu(userId, "m");
        //2、获取所有的一级菜单
        List<MenuInfo> rootMenu=new ArrayList<>();
        for(MenuInfo m:initList){
            if (m.getParentId()==-1){
                rootMenu.add(m);
            }
        }
        //3、设置一级菜单的子菜单
        for(MenuInfo m: rootMenu){
            //调用递归
            m.setChild(getChildren(m.getId(),initList));
        }
        //组装结果
        Map<String,Object> homeInfoMap=new HashMap<>();
        homeInfoMap.put("title","首页");
        homeInfoMap.put("href","page/welcome-1.html");
        Map<String,Object> logoInfoMap=new HashMap<>();
        logoInfoMap.put("title","CRM管理平台");
        logoInfoMap.put("image","images/logo.png");
        logoInfoMap.put("href","");
        Map<String,Object> menuInfoMap=new HashMap<>();
        menuInfoMap.put("title","常规管理");
        menuInfoMap.put("icon","fa fa-address-book");
        menuInfoMap.put("href","");
        menuInfoMap.put("target","_self");
        menuInfoMap.put("child",rootMenu);
        List<Map<String,Object>> mList=new ArrayList<>();
        mList.add(menuInfoMap);

        Map<String,Object> rslMap=new HashMap<>();
        rslMap.put("homeInfo",homeInfoMap);
        rslMap.put("logoInfo",logoInfoMap);
        rslMap.put("menuInfo",mList);
        return rslMap;
    }

    /**
     * 递归查找子菜单
     * @param pid
     * @param all
     * @return
     */
    private List<MenuInfo> getChildren(Integer pid,List<MenuInfo> all){
        List<MenuInfo> children=new ArrayList<>();//子菜单集合
        //、在所有菜单里面找父id=pid的
        for (MenuInfo m:all){
            if(m.getParentId()==pid){
                children.add(m);
            }
        }
        //2、递归找子的子....
        for (MenuInfo m:children){
            m.setChild(getChildren(m.getId(),all));

        }
        //3、递归退出

        if (children.size()==0){
            return new ArrayList<>();
        }
        return  children;
    }
}
